﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Zeus.DAL.NHibernate.Repositories;
using Zeus.Biz.DomainModel.NHib.Northwind;
using NHibernate.Criterion;

namespace Zeus.Biz.DAL.NHib.Northwind
{
    public class NhEmployeeRepository : NhGenericRepository<Employee, int>, IEmployeeRepository
    {
        public IList<Employee> SearchEmployees(string employeeName)
        {
            var query = Session.CreateCriteria<Employee>();

            if (!string.IsNullOrEmpty(employeeName))
            {
                query.Add(PrepareCriteria4ParentName(employeeName));
            }
            return query.List<Employee>();
        }

        private ICriterion PrepareCriteria4ParentName(string employeeName)
        {
            ICriterion criteria = default(ICriterion);
            if (!string.IsNullOrEmpty(employeeName))
            {
                criteria = Subqueries.PropertyIn(Projections.Property<Employee>(c => c.EmployeeID).PropertyName,
                    DetachedCriteria.For<Employee>()
                    .Add(Restrictions.Like(Projections.Property<Employee>(c => c.FirstName), employeeName.ToLikeExp()))
                    .SetProjection(Projections.Property<Employee>(c => c.EmployeeID)));
            }
            return criteria;
        }
    }
}
